﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;

namespace JsonEditor
{
    public static class ExtensionMethods
    {
        public static bool IsExistingProperty(this JToken targetJToken, JToken newJToken)
        {
            if (newJToken.Type == JTokenType.Property)
                return IsExistingProperty(targetJToken, ((JProperty)newJToken).Name);
            else
                return false;
        }
        public static bool IsExistingProperty(this JToken targetJToken, string name)
        {
            if (targetJToken != null && !string.IsNullOrEmpty(name) && targetJToken.Type == JTokenType.Object)
                return ((IDictionary<string, JToken>)targetJToken).Any(pair => pair.Key == name);
            else
                return false;
        }

        public static IEnumerable<JToken> GetJTokenAncestors(this JToken item)
        {
            List<JToken> ancestors = new List<JToken>();
            JToken currentItem = item;

            while (currentItem != null)
            {
                ancestors.Add(currentItem);
                currentItem = currentItem.Parent;

                if (currentItem != null && currentItem.Parent != null && currentItem.Parent.Type == JTokenType.Property)
                    currentItem = currentItem.Parent;
            }

            ancestors.Reverse();

            return ancestors;
        }

        public static bool LowerCaseContains(this string source, string text)
        {
            return source.ToLowerInvariant().Contains(text.ToLowerInvariant());
        }
    }
}
